package tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @ClassName SearchTreeNode
 * @Description TODO
 * @Author lenovo
 * @Date 2023-03-29 11:37
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class SearchTreeNode {
    /**
     * 700. 二叉搜索树中的搜索
     * 给定二叉搜索树（BST）的根节点 root 和一个整数值 val。
     * <p>
     * 你需要在 BST 中找到节点值等于 val 的节点。 返回以该节点为根的子树。 如果节点不存在，则返回 null 。
     * <p>
     * <p>
     * <p>
     * 示例 1:
     * <p>
     * <p>
     * <p>
     * 输入：root = [4,2,7,1,3], val = 2
     * 输出：[2,1,3]
     */


    public TreeNode searchBST(TreeNode root, int val) {

        if (root == null) return null;

        Queue<TreeNode> treeNodeQueue = new LinkedList<>();
        treeNodeQueue.add(root);
        TreeNode treeNode = new TreeNode();
        while (!treeNodeQueue.isEmpty()) {
            int size = treeNodeQueue.size();
            while (size > 0) {
                TreeNode poll = treeNodeQueue.poll();
                if (poll.val == val) {
                    treeNode = poll;
                    return treeNode;
                }
                if (poll.left != null) {
                    treeNodeQueue.add(poll.left);
                }
                if (poll.right != null) {
                    treeNodeQueue.add(poll.right);
                }
                size--;
            }
        }
        return null;
    }


    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(2);
        treeNode.left = new TreeNode(1);
        treeNode.right = new TreeNode(3);
        SearchTreeNode searchTreeNode = new SearchTreeNode();
        System.out.println(searchTreeNode.searchBST(treeNode, 1));
    }
}